﻿using EMall.Query;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace EMall.AuthServer
{
    public class IdentityServerResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly IQueryService _queryService;
        private readonly IPasswordValidator<User> _passwordValidator;
        private readonly UserManager<User> _userManager;
        public IdentityServerResourceOwnerPasswordValidator(IQueryService queryService, IPasswordValidator<User> passwordValidator, UserManager<User> userManager)
        {
            _queryService = queryService;
            _passwordValidator = passwordValidator;
            _userManager = userManager;
        }
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var user = await _queryService.GetQueryable<User>().FirstOrDefaultAsync(o => o.UserName == context.UserName);
            if (user != null)
            {
                var passwordValidateResult = await _passwordValidator.ValidateAsync(_userManager, user, context.Password);
                if (passwordValidateResult.Succeeded)
                {
                    context.Result = new GrantValidationResult(user.Id.ToString(), "custom");
                }
                else
                {
                    context.Result = new GrantValidationResult
                    {
                        IsError = true,
                        Error = "invalid_password(" + string.Join(' ', passwordValidateResult.Errors.Select(o => o.Description)) + ")"
                    };
                }
            }
            else
            {
                context.Result = new GrantValidationResult
                {
                    IsError = true,
                    Error = "invalid_username"
                };
            }
        }
    }
}
